package com.ldy.core.util;

import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;

import com.ldy.core.common.LoginUser;
import com.ldy.core.entity.BaseUser;

public class MySession {
	static {
		System.out.println("我被初始化了=====");
	}

	static class Inner {
		static {
			System.out.println("我被初始化了Inner=====");
		}
		public static final CacheMap<String, BaseUser> cache = new CacheMap<>(60*60*1000);
		
	}
	
	
	
	
	public static String add(BaseUser user) {
		String key = UUID.randomUUID().toString();
		Inner.cache.put(key, user);
		set(user);
		return key;
	}
	public static void reset(String uuid, BaseUser user) {
		Inner.cache.put(uuid, user);
		set(user);
	}
	
	public static void remove(String uuid) {
		Inner.cache.remove(uuid);
		remove();
	}
	
	public static LoginUser get(String key) {
		BaseUser user = Inner.cache.get(key);
		if (user == null) {
			remove();
			return null;
		}
		LoginUser login = new LoginUser();
		BeanUtils.copyProperties(user, login);
		set(user);
		return login;
	}
	
	/**
	 * 本地线程用于存放会话.
	 * 
	 * <pre>
	 * 注意：
	 * 此处【阿里代码规范检查工具】会提示报错：没有调用remove方法回收
	 * 其实该线程回收在baseweb工程中的SecurityInterceptor类中进行了回收
	 * 因此属于误报
	 * </pre>
	 */
	private static ThreadLocal<BaseUser> threadLocal = new ThreadLocal<BaseUser>();

	/**
	 * 获取当前会话线程对象
	 * 
	 * @param session 会话对象
	 * @return MySession
	 */
	public static ThreadLocal<BaseUser> set(@Nullable BaseUser user) {
		threadLocal.set(user);
		return threadLocal;
	}

	/**
	 * 禁止实例化的无参构造
	 */
	private MySession() {
	}

	/**
	 * 获取当前会话对象
	 * 
	 * @return Session
	 */
	public static BaseUser get() {
		return threadLocal.get();
	}

	/**
	 * 删除该会话及本地线程
	 */
	public static void remove() {
		threadLocal.remove();
	}
}
